package com.liruo.treasureattic.common.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * @Author:liruo
 * @Date:2023-02-06-14:10:16
 * @Desc
 */
public class NetUtils {
    /**
     * https://www.github.com/liruohrh
     * https://www.github.com
     */
    public static String getIcoFormUrl(String url, String defaultIco){
        int targetCnt = 0, separatorIndex = url.length();
        for (int i = 0; i < url.length(); i++) {
            if(url.charAt(i) == '/'){
                targetCnt++;
                if(targetCnt == 3){
                    separatorIndex = i;
                    break;
                }
            }
        }
        String ico;
        if(targetCnt == 3 || targetCnt == 2){
            ico = url.substring(0, separatorIndex) + "/favicon.ico";
        }else{
            ico = defaultIco;
        }
        return ico;
    }
    public static InetAddress getLocalUsingNetIp() throws UnknownHostException {
        return InetAddress.getLocalHost();
    }
    public static byte[] getLocalUsingNetMac() throws UnknownHostException, SocketException {
        InetAddress localNetHost = getLocalUsingNetIp();
        NetworkInterface localNetWork = NetworkInterface.getByInetAddress(localNetHost);
        return localNetWork.getHardwareAddress();
    }
    public static String getLocalUsingNetMacString() throws UnknownHostException, SocketException {
        byte[] localUsingNetMac = getLocalUsingNetMac();
        StringBuilder maxStringBuilder = new StringBuilder();
        for (byte m : localUsingNetMac){
            maxStringBuilder.append(Integer.toHexString(BitUtils.stableIntByte(m))).append("-");
        }
        maxStringBuilder.deleteCharAt(maxStringBuilder.length() - 1);
        return maxStringBuilder.toString();
    }
}
